package com.jmp.autocofiguration.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.exception.*;
import one.stand.model.ResultModel;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class DefaultExceptionHandler implements ExceptionHandler {
    @Override
    public void handler(Exception e, HttpServletResponse response) {
        log.error(e.getMessage(), e);
        if (e instanceof LoginException) {
            response(response, ResultEnum.NO_LOGIN, null);
        } else if (e instanceof CompanyException) {
            response(response, ResultEnum.NO_COMPANY, e.getMessage());
        } else if (e instanceof CardException) {
            response(response, ResultEnum.NO_ROLE, null);
        } else if (e instanceof CardNumServiceException) {
            response(response, ResultEnum.CARD_OVERDUE, null);
        } else if (e instanceof BossException) {
            response(response, ResultEnum.NO_BOSS, null);
        } else if (e instanceof TouristException) {
            response(response, ResultEnum.NO_TOURIST, null);
        } else if (e instanceof ParamException) {
            response(response, ResultEnum.PARAM_CHECK, e.getMessage());
        } else if (e instanceof JSONException) {
            response(response, ResultEnum.PARAM_CHECK, null);
        } else if (e instanceof PhoneNotFoundException) {
            response(response, ResultEnum.PARAM_CHECK, e.getMessage());
        } else {
            response(response, ResultEnum.ERROR, null);
        }
    }

    private void response(HttpServletResponse response, ResultEnum resultEnum, String msg) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = null;
        try {
            ResultModel resultModel = StringUtils.isNoneBlank(msg) ? ResultModel.fail(resultEnum.getCode(), msg) : ResultModel.fail(resultEnum);
            String result = JSON.toJSONString(resultModel);
            writer = response.getWriter();
            writer.print(result);
        } catch (IOException e) {
            log.error("response error", e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
